﻿import * as fs from "fs";
import { Hash } from "./hubs/hash";
import { resolve } from "dns";
import { FS } from "./hubs/fs";
import { Server } from "./hubs/server";
import { Encoding } from "./hubs/encoding";
import { Extension } from "./hubs/extension";
import { VSCode } from "./hubs/vscode";
import { Search } from "./hubs/search";
import { TypeScript } from "./hubs/typescript";
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});
var HUBS = [
    Hash, FS, Server, Encoding, Extension, VSCode, Search, TypeScript
];
var hubMethods = {};
HUBS.forEach((HUB: any) => {
    HUB.methods = {};
    var hub = new HUB();
    for (var member in hub) {
        if (typeof hub[member] != "function") {
            continue;
        }
        var method = hub[member];
        HUB.methods[member.toLowerCase()] = method;
    }
});

io.on('connection', function (socket) {
    console.log('a user connected');
    var hubs = HUBS.map(x => {
        var hub = new x();
        (<any>hub).socket = socket;
        return {
            name: x.name.toLocaleLowerCase(),
            hub: hub,
            methods: x["methods"]
        }
    });
    socket.on('disconnect', (reason) => {
        try {
            var typescriptHub = hubs.filter(x => x.name == "typescript")[0];
            (<any>typescriptHub.hub).kill();
        } catch (e) {
            console.error(e);
        }
    });
    hubs.forEach((hubInfo) => {
        socket.on(hubInfo.name, (msg) => {
            var method = hubInfo.methods[msg.method.toLowerCase()];
            var result = method.apply(hubInfo.hub, msg.args);
            if (!result) {
                return;
            }
            var response = {
                success: true,
                result: null,
                message: "",
                hub: hubInfo.name,
                event: "on" + msg.method.toLowerCase() + msg.id
            };
            if (result.then) {
                var p = result;
                p.then((data) => {
                    response.success = true;
                    response.result = data;
                    socket.emit(hubInfo.name, response);
                }, (reason) => {
                    response.success = false;
                    response.result = reason;
                    socket.emit(hubInfo.name, response);
                }).done();
                return;
            }
            response.success = true;
            response.result = result;
            socket.emit(hubInfo.name, response);
        })
    });
});

http.listen(8009, function () {
    console.log('listening on *:8009');
});

require('socketio-auth')(io, {
    authenticate: function (socket, data, callback) {
        var token = data.token;
        console.log("token:" + token);
        callback(null, true);
    }
});